package com.xiaowei.gym.gymjsp.ware.servlet;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.mysql.cj.util.StringUtils;
import com.xiaowei.gym.gymjsp.ware.dto.AdminDTO;
import com.xiaowei.gym.gymjsp.ware.entity.AdminEntity;
import com.xiaowei.gym.gymjsp.ware.service.AdminService;
import com.xiaowei.gym.gymjsp.ware.service.impl.AdminServiceImpl;
import com.xiaowei.gym.gymjsp.ware.util.Constants;
import com.xiaowei.gym.gymjsp.ware.util.ExcelImportListener;
import com.xiaowei.gym.gymjsp.ware.util.PageSupport;
import com.xiaowei.gym.gymjsp.ware.vo.AdminVo;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.*;


@WebServlet("/gymjsp/admin.do")
public class AdminServlet extends HttpServlet {

    private AdminService adminService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get进来了");
        System.out.println(req.getContextPath());
        System.out.println(req.getContentLength());
        System.out.println(req.getScheme());
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("post进来了");
        String method = req.getParameter("method");
        if (method!=null && method.equals("query")){
            System.out.println("query");
            this.query(req,resp);
        }else if (method != null && method.equals("add")){
            System.out.println("adminadd");
            this.add(req,resp);
        }else if (method != null && method.equals("deluser")) {
            this.delUser(req,resp);
        }else if (method != null && method.equals("modify")){
            this.getAdminById(req,resp,"manager/adminmodify.jsp");
        }else if (method != null && method.equals("modifyexe")){
            this.modify(req,resp);
        }else if (method != null && method.equals("view")){
            this.getAdminById(req,resp,"manager/adminview.jsp");
        }else if (method != null && method.equals("validAdmin")){
            this.validAdmin(req,resp);
        }//判断上传的表单是普通表单还是文件表单
        else if (method != null && method.equals("importExcel")){
            this.ImportExcel(req,resp);
        }else if (method != null && method.equals("exportExcel")){
            this.exportExcel(req,resp);
        }
    }

    private void exportExcel(HttpServletRequest req, HttpServletResponse resp) {
        try {
            List<AdminVo> excelAdminVos = adminService.exportExcel(resp);
            if (excelAdminVos.isEmpty() || excelAdminVos.size() == 0) {
                System.out.println("导出成功！");
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    private void validAdmin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String admin = req.getParameter("admin");
        AdminDTO adminDTO = JSON.parseObject(admin, AdminDTO.class);
        if (!StringUtils.isNullOrEmpty(adminDTO.getName()) ||
                !StringUtils.isNullOrEmpty(adminDTO.getPhone()) ||
                !StringUtils.isNullOrEmpty(adminDTO.getEmail())){
            Map<String, Object> map = adminService.validAdmin(adminDTO);
            JSONObject responseJson = new JSONObject();
            String name = null,phone = null,email = null;
            if (map.size() > 0 || !map.isEmpty()){
                if(map.containsKey("name")){
                    name =  map.get("name").toString();
                }
                if (map.containsKey("phone")){
                    phone = map.get("phone").toString();
                }
                if (map.containsKey("email")){
                    email =  map.get("email").toString();
                }
                // 构建响应JSON对象,再次进行非空判断。
                if (!StringUtils.isNullOrEmpty(name)){
                    responseJson.put("name",name);
                }
                if (!StringUtils.isNullOrEmpty(phone)){
                    responseJson.put("phone",phone);
                }
                if (!StringUtils.isNullOrEmpty(email)){
                    responseJson.put("email",email);

                }
                // 设置响应内容类型为JSON
//                responseJson.put("exists",flag);
                resp.setContentType("application/json");
                resp.setCharacterEncoding("UTF-8");
                // 发送响应
                PrintWriter out = resp.getWriter();
                out.print(responseJson);
                out.flush();
                out.close();
            }else {
                responseJson.put("exists",false);
                // 设置响应内容类型为JSON
                resp.setContentType("application/json");
                resp.setCharacterEncoding("UTF-8");
                // 发送响应
                PrintWriter out = resp.getWriter();
                out.print(responseJson.toString());
                out.flush();
                out.close();
            }
        }
    }

    @Override
    public void init() throws ServletException {
        adminService = new AdminServiceImpl();
    }

    private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询用户列表
        //从前端获取数据
        String queryUserName = request.getParameter("queryname");
//        String temp = request.getParameter("queryUserRole");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
        List<AdminEntity> adminList = null;
        //第一次走这个请求，一定是第一页，页面大小是固定的
        //设置页面容量
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize") == null ? String.valueOf(Constants.pageSize) : request.getParameter("pageSize"));
        if (pageSize == null){
            pageSize = Constants.pageSize;
        }
        //默认当前页码
        int currentPageNo = 1;

        if (queryUserName == null) {
            queryUserName = "";
        }
//        if (temp != null && !temp.equals("")) {
//            queryUserRole = Integer.parseInt(temp);
//        }

        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                response.sendRedirect("error.jsp");
            }
        }
        //总数量（表）
        int totalCount = adminService.getAdminCount();
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);  //当前页
        pages.setPageSize(pageSize);            //页面大小
        pages.setTotalCount(totalCount);        //总数量

        int totalPageCount = pages.getTotalPageCount();  //总页面数量

        //控制首页和尾页
        //如果页面小于第一页，就显示第一页
        if (currentPageNo < 1) {
            currentPageNo = 1;
            //如果当前页面大于最后一页，当前页等于最后一页即可
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        //获取管理员列表展示
        adminList = adminService.getAdminList(queryUserName, currentPageNo, pageSize);
        System.out.println(adminList);
        request.setAttribute("adminList", adminList);
        request.setAttribute("queryUserName", queryUserName);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("currentPageNo", currentPageNo);
        request.getRequestDispatcher("manager/admin.jsp").forward(request, response);
    }

    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        AdminEntity adminEntity = new AdminEntity();
        adminEntity.setUsername(userName);
        adminEntity.setPassword(userPassword);
        int admin = adminService.createAdmin(adminEntity);
        if (admin > 0) {
            System.out.println(request.getContextPath());
            response.sendRedirect(request.getContextPath() + "/gymjsp/admin.do?method=query");
        } else {
            request.getRequestDispatcher("manager/useradd.jsp").forward(request, response);
        }

    }

    public void delUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String id = request.getParameter("uid");
        System.out.println("获取到的id:"+id);
        String[] ids = JSON.parseObject(id,String[].class);
        Integer[] delId = new Integer[ids.length];
        try {
            delId = Arrays.stream(ids)
                    .mapToInt(Integer::parseInt)
                    .boxed()
                    .toArray(Integer[]::new);
            System.out.println("delId长度:"+delId.length);
            System.out.println("delId:"+delId.toString());
        } catch (Exception e) {
            // TODO: handle exception
            delId[0] = 0;
        }
        HashMap<String, String> resultMap = new HashMap<>();
        if (delId.length <= 0 ) {
            resultMap.put("delResult", "notexist");
        } else {
            if (adminService.deleteAdminByIds(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        //把resultMap转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        Gson gson = new Gson();
        outPrintWriter.write(gson.toJson(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    private void getAdminById(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException {
        String id = request.getParameter("aid");
        if (!StringUtils.isNullOrEmpty(id)) {
            //调用后台方法得到user对象
            AdminEntity admin = adminService.getAdminById(Integer.valueOf(id));
            request.setAttribute("admin", admin);
            request.getRequestDispatcher(url).forward(request, response);
        }
    }

    public void modify(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        System.out.println("modify进来了");
        String aid = request.getParameter("aid");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        AdminEntity adminEntity = new AdminEntity();
        adminEntity.setId(Integer.valueOf(aid));
        adminEntity.setUsername(userName);
        adminEntity.setPassword(password);
        adminEntity.setUpdatetime(new Date());
        if (adminService.modify(adminEntity)) {
            response.sendRedirect(request.getContextPath() + "/gymjsp/admin.do?method=query");
        } else {
            request.getRequestDispatcher("manager/adminmodify.jsp").forward(request, response);
        }
    }

    public void ImportExcel(HttpServletRequest request,HttpServletResponse response) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        // 读取全部sheet
        // 这里需要注意 ExcelImportListener的doAfterAllAnalysed 会在每个sheet读取完毕后调用一次。然后所有sheet都会往同一个ExcelImportListener里面写
        EasyExcel.read(
                inputStream,
                AdminDTO.class,
                new ExcelImportListener(adminService)).doReadAll();
//        String filename = file.getOriginalFilename();
//        String extendName = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
//        log.info("exetend"+extendName);
//        if ("xlsx".equals(extendName) || "xls".equals(extendName)){
//
//        }
    }
}
